package com.example.presentshopping.ui.fragment.frgmentdlog

import android.Manifest
import android.app.Dialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.os.Handler
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder
import com.example.presentshopping.R
import com.example.presentshopping.config.base.BaseFragmentDialog
import com.example.presentshopping.config.base.MyApplication
import com.example.presentshopping.mvp.presenter.PublicGetTask
import com.example.presentshopping.net.http.HttpRequest
import com.example.presentshopping.net.http.HttpURL
import com.example.presentshopping.net.observer.TaskCallback
import com.example.presentshopping.ui.activity.GoldSActivity
import com.example.presentshopping.ui.activity.SetupPayPwdCheckActivity
import com.example.presentshopping.ui.custom.PayPwdEditText
import com.example.presentshopping.ui.dialog.MessageDialog
import com.example.presentshopping.utils.ShareUtils
import com.example.presentshopping.utils.ToastUtil
import com.example.presentshopping.utils.tool.ViewSetUtils
import com.example.presentshopping.utils.tool.unit.DensityUtil
import com.permissionx.guolindev.PermissionX
import com.yun.utils.image.ImageUtils
import com.yun.utils.image.SizeUtils
import org.json.JSONObject


class RedEnvelopeDialog(var activity: AppCompatActivity) : BaseFragmentDialog() {
    private var walletDialog: Dialog? = null

    private var queryInfoPresenter: PublicGetTask? = null

    private var bitmap_1: Bitmap? = null

    override fun initView(view: View?, savedInstanceState: Bundle?) {
        queryInfoPresenter = PublicGetTask(context, true)
        val exieshon = view?.findViewById<EditText>(R.id.exieshon)
        val but_liji = view?.findViewById<Button>(R.id.but_liji)

        but_liji?.isClickable = false

        exieshon?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                //如果第一个数字为0，第二个不为点，就不允许输入
                if (s.toString().startsWith("0") && s.toString().trim().length > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        exieshon.setText(s?.subSequence(0, 1));
                        exieshon.setSelection(1);
                        return;
                    }
                }
                //如果第一为点，直接显示0.
                if (s.toString().startsWith(".")) {
                    exieshon.setText("8.");
                    exieshon.setSelection(2);
                    return
                }

                //限制输入小数位数(2位)
                if (s.toString().contains(".")) {
                    if (s?.length!! - 1 - s.toString().indexOf(".") > 2) {
                        var s = s.toString().subSequence(0, s.toString().indexOf(".") + 2 + 1);
                        exieshon.setText(s);
                        exieshon.setSelection(s.length);
                    }
                }
                Log.e("selected", s.toString())

                if (!TextUtils.isEmpty(s)) {
                    if (s.toString().toDouble() in 8..99) {
                        if (s.toString().toDouble() > 99) {
                            but_liji?.setTextColor(Color.parseColor("#999999"))
                            but_liji?.isClickable = false
                        } else {
                            but_liji?.setTextColor(Color.parseColor("#D10505"))
                            but_liji?.isClickable = true
                        }
                    } else {
                        but_liji?.setTextColor(Color.parseColor("#999999"))
                        but_liji?.isClickable = false
                    }
                } else {
                    but_liji?.setTextColor(Color.parseColor("#999999"))
                    but_liji?.isClickable = false
                }
            }

            override fun afterTextChanged(s: Editable?) {


            }
        })
        but_liji?.setOnClickListener {
            ViewSetUtils.ButtonClickZoomInAnimation(view, 0.90f)
            if (ActivityCompat.checkSelfPermission(
                    context!!,
                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            ) {
                PermissionX.init(activity)
                    .permissions(
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    )
                    .onExplainRequestReason { scope, deniedList ->
//                        val message = "需要您同意以下权限才能正常使用"
//                        scope.showRequestReasonDialog(deniedList, message, "确定", "取消")
                    }
                    .request { allGranted, grantedList, deniedList ->
                        if (allGranted) {
                            if (!TextUtils.isEmpty(exieshon?.text.toString())) {
                                showEditPayPwdDialog(exieshon?.text.toString())
                            }
                        } else {

                        }
                    }

            } else {
                if (!TextUtils.isEmpty(exieshon?.text.toString())) {
                    showEditPayPwdDialog(exieshon?.text.toString())
                }
            }
        }
    }

    override val layoutId: Int
        get() = R.layout.red_dialog



    //平台支付
    fun showEditPayPwdDialog(order_id: String) {
        val view: View = layoutInflater.inflate(R.layout.dialog_layout, null)
        walletDialog = context?.let { Dialog(it, R.style.walletFrameWindowStyle) }
        walletDialog!!.setContentView(
            view, ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
        )

        val window = walletDialog!!.window
        val wl = window!!.attributes

        //紧贴软键盘弹出
        wl.gravity = Gravity.BOTTOM
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT
        walletDialog!!.onWindowAttributesChanged(wl)
        walletDialog!!.setCanceledOnTouchOutside(false)
        walletDialog!!.show()


        //忘记密码 按钮
        view.findViewById<View>(R.id.tv_forgetPwd).setOnClickListener {
            startActivity(
                Intent(
                    context,
                    SetupPayPwdCheckActivity::class.java
                )
            )
        }
        val ppet: PayPwdEditText = view.findViewById(R.id.dialog_ppet)
        val img_cancle = view.findViewById<ImageView>(R.id.img_cancle)
        //调用initStyle方法创建你需要设置的样式
        //调用initStyle方法创建你需要设置的样式
        ppet.initStyle(R.drawable.edit_num_bg, 6, 0.33f, R.color.gray, R.color.black, 30)
        img_cancle.setOnClickListener {
            walletDialog!!.dismiss()
            //手动收起软键盘
            val imm =
              context?.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(ppet.windowToken, 0)
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)

        }

        ppet.setOnTextFinishListener {
            //密码输入完后的回调
            walletDialog!!.dismiss()
            //手动收起软键盘
            val imm =   context?.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(ppet.windowToken, 0)
            //可在此执行下一步操作
            val paypass = ppet.pwdText
            order_id?.let { it1 -> setBitMap(it1, paypass) }

        }
        //延迟弹起软键盘，使PayPwdEditText获取焦点
        Handler().postDelayed({ ppet.setFocus() }, 100)

    }


    fun setBitMap(amount: String, password: String) {
        queryInfoPresenter?.netWorkRequestPost(HttpURL.Req_getInvitationCode,
            HttpRequest.getInvitationCode(amount, password), object : TaskCallback {
                override fun onSuccess(data: String?) {
                    var json = JSONObject(data).getString("register_url")
                    Log.e("ComesQCasActivity", json)
                    RCDemo(json)
                }

                override fun onFailure(
                    e: Throwable?,
                    code: Int,
                    msg: String?,
                    isNetWorkError: Boolean
                ) {
                  if (code==999){
                      dismiss()
                      diaDlog(msg)
                      ToastUtil.showMsg(msg)

                  }
                }

            })
    }
    //合成图片
    fun mergeBitmap(
        firstBitmap: Bitmap?,
        secondBitmap: Bitmap?,
        width: Float,
        height: Float,
        type: Int
    ): Bitmap? {
        if (firstBitmap == null || secondBitmap == null) return null
        val bitmap = Bitmap.createBitmap(
            firstBitmap.width, firstBitmap.height,
            Bitmap.Config.ARGB_8888
        )
        val canvas = Canvas(bitmap)
        canvas.drawBitmap(firstBitmap, 0f, 0f, null)
        //NULL

        when (type) {
            0, 1 -> {
                // 画笔。
                val paint = Paint()
                paint.color = Color.WHITE
                paint.style = Paint.Style.FILL
                paint.strokeWidth = 12f
                paint.textSize = SizeUtils.dip2px(activity, 20f)
                val msg = ""
                //绘制到图片上。在图片上位置
                canvas.drawText(
                    msg,
                    SizeUtils.dip2px(activity, 0f),
                    SizeUtils.dip2px(activity, 0f),
                    paint
                )
            }
            2 -> {
                val paint = Paint()
                paint.color = Color.WHITE
                paint.style = Paint.Style.FILL
                paint.strokeWidth = 12f
                paint.textSize = SizeUtils.dip2px(activity, 20f)
                val msg = ""
                canvas.drawText(
                    msg,
                    SizeUtils.dip2px(activity, 30f),
                    SizeUtils.dip2px(activity, 20f),
                    paint
                )
            }

        }
        canvas.save()
        canvas.drawBitmap(secondBitmap, width, height, null)
        canvas.restore()
        return bitmap
    }


    fun RCDemo(url: String) {
        val logoBitmap = BitmapFactory.decodeResource(resources, R.mipmap.iconi)
        val logoBm = QRCodeEncoder.syncEncodeQRCode(
            url, DensityUtil.dip2px(MyApplication.getContext(), 100f),
            Color.parseColor("#333333"), logoBitmap)
        val bm1 = (resources.getDrawable(R.mipmap.fenx2) as BitmapDrawable).bitmap
        bitmap_1 = mergeBitmap(bm1, logoBm, SizeUtils.dip2px(activity, 88f), SizeUtils.dip2px(activity,
            360f), 0)

        var file = ImageUtils.saveImageToFile(activity, bitmap_1!!, "invite_face.jpg")
        ShareUtils.shareWechatFriend(context, "" + file)
        dialog?.dismiss()
    }
  fun  diaDlog(msg :String?){
      MessageDialog.Builder(activity)
          .setMessage(msg)
          .setCancel("兑换金币")
          .setConfirm("取消")
          .setListener(object :MessageDialog.OnListener{
              override fun onConfirm(dialog: Dialog?) {

              }

              override fun onCancel(dialog: Dialog?) {
                  activity.startActivity(Intent(activity , GoldSActivity().javaClass))
              }

          }).show()
  }

}